from threading import Thread, Lock
import time

# 线程
li = []


def wdata():
    for i in range(5):
        li.append(i)
        time.sleep(0.2)
        print("写入数据：", li)


def rdata():
    print("读取数据：", li)


if __name__ == '__main__':
    # 创建子线程
    t1 = Thread(target=wdata)
    t2 = Thread(target=rdata)
    # 开启子线程
    t1.start()
    # 阻塞线程 加了 join() 会等待 t1任务执行结束
    t1.join()
    # time.sleep(1)
    t2.start()

a = 0
b = 10000000


def add():
    for i in range(b):
        global a
        a += 1
    print("第一次：", a)


def add2():
    for i in range(b):
        global a
        a += 1
    print("第二次：", a)


# add()
# add2()

# if __name__ == "__main__":
#     first = Thread(target=add)
#     second = Thread(target=add2)
#     first.start()
#     second.start()
# 线程同步
# 方式1 join()
#
if __name__ == "__main__":
    first = Thread(target=add)
    second = Thread(target=add2)
    first.start()
    first.join()
    second.start()
# 互斥锁 acquire() 加锁 release() 解锁
locK = Lock()
c = 0
d = 10000000


def add():
    locK.acquire()  # 上锁
    for i in range(d):
        global c
        c += 1
    print("第一次：", c)
    locK.release()  # 解锁


def add2():
    locK.acquire()
    for i in range(d):
        global c
        c += 1
    print("第二次：", c)
    locK.release()


if __name__ == "__main__":
    first = Thread(target=add)
    second = Thread(target=add2)
    first.start()
    first.join()
    second.start()
